package com.hmjk.health.card;

import com.hmjk.health.R;
import com.hmjk.health.util.DEV_DATA;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class InterestDeviceDialog extends Dialog implements android.view.View.OnClickListener{
	private Context mContext;
	private static InterestDeviceDialog mSelf;
	private EditText mName;
	private TextView mDefName;
	private static DEV_DATA mDev;
	private LinearLayout bok;
	private LinearLayout bcancel;
	private static boolean mToBeApply = false;
	
	public interface OnInterestDialogDismissListener{
		public void onDismiss(boolean toBeApply, DEV_DATA data);
	};
	
	protected InterestDeviceDialog(Context context, int theme) {
		super(context,theme);
		mContext = context;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.apply_interest_dev, null);
		setContentView(v);
		
		Window win = getWindow();
		win.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
		win.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		
		mDefName = (TextView) v.findViewById(R.id.devname);
		mDefName.setText(mDev.name);
		mName = (EditText) v.findViewById(R.id.name);
		mName.setText(mDev.name);
		int pos = mDev.name.length();
		mName.setSelection(pos);
		
		bok = (LinearLayout) v.findViewById(R.id.but_ok);
		bcancel = (LinearLayout) v.findViewById(R.id.but_cancel);

		bok.setOnClickListener(this);
		bcancel.setOnClickListener(this);
		mToBeApply = false;
	}
	
	public static void open(Context context, String tid, String name, final OnInterestDialogDismissListener l){
		mDev = new DEV_DATA();
		mDev.id = tid;
		mDev.name = name;
		
		if(mSelf == null){
			mSelf = new InterestDeviceDialog(context, R.style.CustomDialog);
		}
		mSelf.setCanceledOnTouchOutside(false);
		mSelf.setCancelable(true);
		mSelf.setOnDismissListener(new OnDismissListener(){

			@Override
			public void onDismiss(DialogInterface arg0) {
				if(l != null){
					l.onDismiss(mToBeApply, mDev);
				}
				mDev = null;
				mToBeApply = false;
				mSelf = null;
			}
			
		});
		mSelf.show();
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.but_ok){
			String name = mName.getText().toString();
			if((name != null) && (!name.trim().isEmpty())){
				mDev.name = name;
			}
			mToBeApply = true;
			mSelf.dismiss();
			
		}else if(v.getId() == R.id.but_cancel){
			mToBeApply = false;
			mSelf.dismiss();
		}
	}
}
